package com.haozi.ehub.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.haozi.ehub.core.enums.ExceptionEnum;
import com.haozi.ehub.core.enums.HttpEunm;
import com.haozi.ehub.core.exception.UsernameOrPasswordErrorException;
import com.haozi.ehub.core.model.User;
import com.haozi.ehub.core.util.*;
import com.haozi.ehub.entity.entities.ReturnData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 登陆成功,用bean形式使用
 * @author ：terry
 * @date ：Created in 2020/6/23 14:07
 * @description：TODO
 * @version: 1.0
 */
@Slf4j
@SuppressWarnings(value = "all")
public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        log.info("Execute pacakage core handler securityAuthenticationSuccessHandler");
        String msg = HttpEunm.LOGIN_SUCCESS.getMsg();

        //获取验证通过的用户信息
        User principal = (User) authentication.getPrincipal();
        //这段代码好像可以不用要,但写上去显得思维比较严谨 o(￣ヘ￣o＃)
        if (principal == null){
            throw new UsernameOrPasswordErrorException(ExceptionEnum.USER_IS_NULL.getEnmsg());
        }
        principal.setPassword(null);
        //将用户信息封装成map,该map作为JWT的载荷内容
        Map<String,Object> dataMap = new HashMap<>();
        //dataMap.put(CodeUtils.USER,principal);
        //加密权限
        String authJson = JSONObject.toJSONString(principal.getAuthorities());
        String encryptAuthJson = RSAEncoderUtils.encrypt(authJson);
        dataMap.put(CodeUtils.AUTH_CLAIMS,encryptAuthJson);
        //创建提供给用户的JWTtoken
        String token = JWTUtils.createToken(principal.getEncryptName(), dataMap);
        //将token设置进入用户信息当中
        principal.setToken(token);

        //创建返回数据的json格式对象
        ReturnData returnData = ReturnDataUtils.returnDataSuccess(principal, msg);
        //将json格式对象转换成json字符串
        String json = JSONObject.toJSONString(returnData);

        //解决跨域
        ResponseUtils.setHttpSerlvetResponse(httpServletResponse);

        //输出返回结果的JSON
        PrintWriter writer = httpServletResponse.getWriter();
        //输出json
        writer.write(json);
        writer.flush();
    }
}
